package com.annotationAndReflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//分析性能问题
public class TestPerformanceAnls {
        //通过普通方式
        public static void test01(){
            User user = new User();
            long start =System.currentTimeMillis();
            for (int i = 0; i < 1000000000; i++) {
                user.getName();//执行10亿次 获取user的名字
            }
            long end = System.currentTimeMillis();
            System.out.println("普通方式执行10亿次:"+(end-start));
         }
        //通过反射方式
        public static void test02() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
            User user = new User();
            Class c1 = user.getClass();
            //获取得到名字的方法
            Method getName = c1.getDeclaredMethod("getName", null);

            long start =System.currentTimeMillis();
            for (int i = 0; i < 1000000000; i++) {
                getName.invoke(user,null);
            }
            long end = System.currentTimeMillis();
            System.out.println("反射方式执行10亿次:"+(end-start));
        }
        //通过关闭安全检查的反射方式
        public static void test03() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
            User user = new User();
            Class c2 = user.getClass();

            //获取得到名字的方法
            Method getName = c2.getDeclaredMethod("getName", null);
            //关闭检查
            getName.setAccessible(true);
            long start =System.currentTimeMillis();
            for (int i = 0; i < 1000000000; i++) {
                getName.invoke(user,null);
            }
            long end = System.currentTimeMillis();
            System.out.println("反射方式+关闭检查执行10亿次:"+(end-start));
        }
        public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
           test01();
           test02();
           test03();
            // 普通方式执行10亿次:4
            //反射方式执行10亿次:2483
            //反射方式+关闭检查执行10亿次:1686
        }
}

    